require 'digest/sha1'

class Employee < ActiveRecord::Base
 validates_presence_of	:username
 validates_uniqueness_of :username

 attr_accessor :password_confirmation

 validates_confirmation_of :password

 def validate
 	errors.add_to_base("Missing password") if :password.blank?
 end

 def password
    @password
 end

 def password=(pwd)
    @password = pwd
    create_new_salt
    self.hashed_password = Employee.encrypted_password(self.password, self.salt)
 end

 def self.authenticate(name, password)
 	employee = self.find_by_username(name)
 	if employee
 		expected_password = encrypted_password(password, employee.salt)
 		if employee.hashed_password != expected_password
 			employee = nil
 		end
	end
	employee
 end

 def after_destroy
	if Employee.count.zero?
		raise "Can't delete the last employee"
 	end
 end

def self.search(search)
  search_condition = "%" + search + "%"
  find(:all, :conditions => ['first_name LIKE ? OR last_name LIKE ? OR username LIKE ? OR phone LIKE ? OR email LIKE ?', search_condition, search_condition, search_condition, search_condition, search_condition])
end

 private

 def self.encrypted_password(password, salt)
 	string_to_hash = password + "tinactin" + salt
 	Digest::SHA1.hexdigest(string_to_hash)
 end

 def create_new_salt
 	self.salt = self.object_id.to_s + rand.to_s
 end
end

